package sample.provider;

import sample2.provider.MyDatabase.MyTable;
import sample2.provider.dml.SQLDeleteBuilder;
import sample2.provider.dml.SQLInsertBuilder;
import sample2.provider.dml.SQLQueryBuilder;
import sample2.provider.dml.SQLUpdateBuilder;
import sample2.provider.dml.SQLWhereBuilder;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class ContentProviderActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Uri uri = MyTable.CONTENT_URI;

		SQLInsertBuilder ib = new SQLInsertBuilder(uri);
		ib.addContentValue(MyTable.Columns.NAME, "abc");
		ib.addContentValue(MyTable.Columns.AGE, 30);
		Uri insertedUri = ib.insert(getContentResolver());
		Log.d("TAG", "1----------------" + insertedUri);

		SQLInsertBuilder ib2 = new SQLInsertBuilder(uri);
		ib2.addContentValue(MyTable.Columns.NAME, "def");
		ib2.addContentValue(MyTable.Columns.AGE, 20);
		insertedUri = ib2.insert(getContentResolver());
		Log.d("TAG", "2----------------" + insertedUri);

		SQLInsertBuilder ib3 = new SQLInsertBuilder(uri);
		ib3.addContentValue(MyTable.Columns.NAME, "ghi");
		ib3.addContentValue(MyTable.Columns.AGE, 10);
		insertedUri = ib3.insert(getContentResolver());
		Log.d("TAG", "3----------------" + insertedUri);

		SQLWhereBuilder where = new SQLWhereBuilder();
		where.addAndEquals(MyTable.Columns.NAME, "def");

		SQLUpdateBuilder ub = new SQLUpdateBuilder(uri);
		ub.addContentValue(MyTable.Columns.AGE, 21);
		ub.setWhere(where);
		int updatedRows = ub.update(getContentResolver());
		Log.d("TAG", "4----------------" + updatedRows);

		SQLDeleteBuilder db = new SQLDeleteBuilder(uri);
		ub.setWhere(where);
		int deletedRows = db.delete(getContentResolver());
		Log.d("TAG", "5----------------" + deletedRows);

		SQLQueryBuilder qb = new SQLQueryBuilder(uri);
		qb.addProjection(MyTable.Columns._ID);
		qb.addProjection(MyTable.Columns.NAME);
		qb.addProjection(MyTable.Columns.AGE);
		//
		qb.addSortOrder(MyTable.Columns.AGE);

		Cursor cursor = qb.query(getContentResolver());
		if (cursor != null) {
			while (cursor.moveToNext()) {
				Log.d("TAG", "----------------");
				Log.d("TAG", "_id :" + cursor.getLong(cursor.getColumnIndex(MyTable.Columns._ID)));
				Log.d("TAG", "name:" + cursor.getString(cursor.getColumnIndex(MyTable.Columns.NAME)));
				Log.d("TAG", "age :" + cursor.getInt(cursor.getColumnIndex(MyTable.Columns.AGE)));

			}
			cursor.close();
		}

	}
}